<template>
  <div class="result-page">
    <el-card class="result-card" shadow="hover">
      <!-- 成功状态 -->
      <div v-if="isSuccess" class="success-content">
        <div class="icon-wrapper">
          <el-icon class="success-icon"><SuccessFilled /></el-icon>
        </div>
        <h2>支付成功 🎉</h2>
        <p class="description">感谢您的购买，页面将自动跳转...</p>

        <el-divider />

        <div class="order-info">
          <p><span class="label">订单编号：</span>{{ orderData.trade_no }}</p>
          <p><span class="label">交易号：</span>{{ orderData.transaction_id || '无' }}</p>
          <p><span class="label">支付金额：</span>¥{{ orderData.actual }}</p>
          <p><span class="label">支付时间：</span>{{ orderData.pay_time }}</p>
        </div>
      </div>

      <!-- 失败状态 -->
      <div v-else class="fail-content">
        <div class="icon-wrapper">
          <el-icon class="fail-icon"><CircleCloseFilled /></el-icon>
        </div>
        <h2>支付失败 ❌</h2>
        <p class="description">{{ failMessage }}</p>

        <el-divider />

        <div class="order-info">
          <p><span class="label">订单编号：</span>{{ orderData.trade_no }}</p>
          <p v-if="orderData.transaction_id"><span class="label">交易号：</span>{{ orderData.transaction_id }}</p>
        </div>
      </div>

      <!-- 倒计时和操作按钮 -->
      <div class="countdown">
        跳转至{{ redirectPageName }}：
        <el-countdown :value="deadline" format="s 秒" @finish="onFinish">
          <template #default="{ seconds }">
            <strong>{{ seconds }}</strong> 秒
          </template>
        </el-countdown>
      </div>

      <div class="actions">
        <el-button
            v-if="isSuccess"
            type="primary"
            @click="goNow"
        >
          立即前往
        </el-button>
        <el-button
            v-else
            type="danger"
            @click="retryPayment"
        >
          重新支付
        </el-button>
        <el-button
            plain
            @click="goHome"
        >
          返回首页
        </el-button>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { SuccessFilled, CircleCloseFilled } from '@element-plus/icons-vue'
import request from '@/utils/'

// 倒计时初始为 5 秒
const countdownSeconds = 5
const deadline = ref(Date.now() + countdownSeconds * 1000)

const route = useRoute();
const router = useRouter()

const orderData = ref({
  order_id: '',
  status: '',
  actual: '0.00',
  trade_no: '',
  pay_time: '',
  transaction_id: '',
  order_type: 1
})
const failMessage = ref('支付过程中出现问题')
const loading = ref(true)

// 计算属性判断是否成功
const isSuccess = computed(() => {
  return orderData.value.status === 'success';
});

// 计算跳转页面名称
const redirectPageName = computed(() => {
  return orderData.value.order_type === 1 ? '钱包页面' : '我的云手机'
})

// 获取订单状态
const fetchOrderStatus = async () => {
  try {
    console.log('完整 route.query',route.query)
    if (!route || !route.query || !route.query.out_trade_no) {
      failMessage.value = '订单号缺失，请检查支付链接';
      loading.value = false;
      return;
    }
    const outTradeNo = decodeURIComponent(route.query.out_trade_no)
    const res = await request.get(`/order/status?trade_no=${outTradeNo}`)
    // const res = await request.get(`/order/status?trade_no=${route.query.out_trade_no}`)
    if (res.code === 200) {
      orderData.value = res.data
    } else {
      failMessage.value = res.msg || '获取订单状态失败'
    }
  } catch (error) {
    failMessage.value = '网络错误，请稍后重试'
    console.error('获取订单状态失败:', error)
  } finally {
    loading.value = false
  }
}

// 根据订单类型跳转不同页面
const redirectToPage = () => {
  if (orderData.value.order_type === 1) {
    router.replace({ path: '/wallet' })
  } else {
    router.replace({ path: '/my_phone' })
  }
}

onMounted(async () => {
  await fetchOrderStatus()
  // 重置倒计时
  deadline.value = Date.now() + countdownSeconds * 1000
})

function onFinish() {
  redirectToPage()
}

function goNow() {
  redirectToPage()
}

function retryPayment() {
  router.push({
    path: '/payment',
    query: { out_trade_no: orderData.value.trade_no }
  });
}

function goHome() {
  router.replace({ path: '/' })
}
</script>

<style scoped>
.result-page {
  min-height: 70vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background: #f5f7fa;
  padding: 16px;
}

.result-card {
  width: 100%;
  max-width: 450px;
  padding: 24px;
  text-align: center;
}

.icon-wrapper {
  margin-bottom: 16px;
}

.success-icon {
  font-size: 48px;
  color: #67c23a;
}

.fail-icon {
  font-size: 48px;
  color: #f56c6c;
}

.description {
  margin: 0;
  color: #606266;
}

.order-info {
  text-align: left;
  margin: 16px 0;
  padding: 0 16px;
}

.order-info p {
  margin: 8px 0;
}

.label {
  display: inline-block;
  width: 80px;
  color: #909399;
}

.countdown {
  margin: 24px 0;
  font-size: 18px;
}

.actions {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.actions .el-button {
  width: 100%;
}
</style>